<template>
  <div class="statistics-container">
    <div class="content-wrapper">
      <div class="statistics-header">
        <div class="header-content">
          <div class="header-text">
            <h1 class="page-title">会议数据统计</h1>
            <p class="page-subtitle">实时数据分析与可视化展示</p>
          </div>
        </div>
      </div>

      <!-- 统计卡片区域 -->
      <div class="statistics-overview">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card total-conferences">
              <div class="stat-icon">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-label">总会议数</div>
                <div class="stat-number">{{ totalConferences }}</div>
                <div class="stat-unit">场会议</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card published-conferences">
              <div class="stat-icon">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-label">已发布会议</div>
                <div class="stat-number">{{ publishedConferences }}</div>
                <div class="stat-unit">场会议</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card upcoming-conferences">
              <div class="stat-icon">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-label">即将举行</div>
                <div class="stat-number">{{ upcomingConferences }}</div>
                <div class="stat-unit">场会议</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card total-venues">
              <div class="stat-icon">
                <el-icon><Location /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-label">总场地数</div>
                <div class="stat-number">{{ totalVenues }}</div>
                <div class="stat-unit">个场地</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="charts-grid">
        <!-- 状态分布 -->
        <div class="chart-wrapper status-distribution">
          <div class="chart-header">
            <h3>会议状态分布</h3>
            <p class="chart-description">各状态会议数量占比分析</p>
          </div>
          <div ref="pieChartRef" class="chart-content"></div>
        </div>

        <!-- 场地使用情况 -->
        <div class="chart-wrapper venue-usage">
          <div class="chart-header">
            <h3>场地使用情况</h3>
            <p class="chart-description">各场地会议举办频次统计</p>
          </div>
          <div ref="barChartRef" class="chart-content"></div>
        </div>

        <!-- 时间分布 -->
        <div class="chart-wrapper time-distribution">
          <div class="chart-header">
            <h3>会议时间分布</h3>
            <p class="chart-description">近12个月会议数量趋势分析</p>
          </div>
          <div ref="lineChartRef" class="chart-content"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { Calendar, Check, Timer, Location } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const totalConferences = ref(0)
const publishedConferences = ref(0)
const upcomingConferences = ref(0)
const totalVenues = ref(0)

const pieChartRef = ref(null)
const barChartRef = ref(null)
const lineChartRef = ref(null)

let pieChart = null
let barChart = null
let lineChart = null

const fetchStatistics = async () => {
  try {
    const response = await request({
      url: '/api/conferences/statistics',
      method: 'get'
    })
    console.log('基础统计数据响应:', response)
    
    if (response && typeof response === 'object') {
      totalConferences.value = response.totalConferences || 0
      publishedConferences.value = response.publishedConferences || 0
      upcomingConferences.value = response.upcomingConferences || 0
      totalVenues.value = response.totalVenues || 0
    }
  } catch (error) {
    console.error('获取基础统计数据失败:', error)
    ElMessage.error('获取基础统计数据失败: ' + (error.response?.data?.message || error.message))
  }
}

const initPieChart = async () => {
  try {
    const response = await request({
      url: '/api/conferences/status-distribution',
      method: 'get'
    })
    console.log('状态分布数据响应:', response)
    
    if (pieChartRef.value && response && typeof response === 'object') {
      pieChart = echarts.init(pieChartRef.value)
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}场 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'center'
        },
        series: [{
          name: '会议状态',
          type: 'pie',
          radius: ['50%', '70%'],
          center: ['60%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{c}场 ({d}%)'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          data: [
            { 
              value: response.DRAFT || 0, 
              name: '未发布', 
              itemStyle: { color: '#909399' } 
            },
            { 
              value: response.PUBLISHED || 0, 
              name: '已发布', 
              itemStyle: { color: '#67C23A' } 
            },
            { 
              value: response.ENDED || 0, 
              name: '已结束', 
              itemStyle: { color: '#E6A23C' } 
            }
          ]
        }]
      }
      pieChart.setOption(option)
      pieChart.resize()
    }
  } catch (error) {
    console.error('获取会议状态分布数据失败:', error)
    ElMessage.error('获取会议状态分布数据失败: ' + (error.response?.data?.message || error.message))
  }
}

const initBarChart = async () => {
  try {
    const response = await request({
      url: '/api/conferences/venue-usage',
      method: 'get'
    })
    console.log('场地使用数据响应:', response)
    
    if (barChartRef.value && Array.isArray(response)) {
      barChart = echarts.init(barChartRef.value)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: response.map(item => item.venueName || '未知场地'),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '使用次数',
          minInterval: 1
        },
        series: [{
          name: '使用次数',
          type: 'bar',
          barWidth: '60%',
          data: response.map(item => ({
            value: item.usageCount || 0,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#4CAF50' },
                { offset: 1, color: '#81C784' }
              ])
            }
          })),
          label: {
            show: true,
            position: 'top'
          }
        }]
      }
      barChart.setOption(option)
      barChart.resize()
    }
  } catch (error) {
    console.error('获取场地使用数据失败:', error)
    ElMessage.error('获取场地使用数据失败: ' + (error.response?.data?.message || error.message))
  }
}

const initLineChart = async () => {
  try {
    const response = await request({
      url: '/api/conferences/time-distribution',
      method: 'get'
    })
    console.log('时间分布数据响应:', response)
    
    if (lineChartRef.value && Array.isArray(response)) {
      lineChart = echarts.init(lineChartRef.value)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: response.map(item => `${item.month}月`),
          axisLabel: {
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '会议数量',
          minInterval: 1
        },
        series: [{
          name: '会议数量',
          type: 'line',
          smooth: true,
          data: response.map(item => item.count || 0),
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(25,118,210,0.5)' },
              { offset: 1, color: 'rgba(25,118,210,0.05)' }
            ])
          },
          itemStyle: {
            color: '#1976D2'
          }
        }]
      }
      lineChart.setOption(option)
      lineChart.resize()
    }
  } catch (error) {
    console.error('获取会议时间分布数据失败:', error)
    ElMessage.error('获取会议时间分布数据失败: ' + (error.response?.data?.message || error.message))
  }
}

onMounted(async () => {
  try {
    await fetchStatistics()
    
    // 确保DOM已经渲染完成后再初始化图表
    nextTick(async () => {
      await Promise.all([
        initPieChart(),
        initBarChart(),
        initLineChart()
      ])
      
      // 监听窗口大小变化
      window.addEventListener('resize', handleResize)
    })
  } catch (error) {
    console.error('初始化统计页面失败:', error)
    ElMessage.error('初始化统计页面失败，请刷新重试')
  }
})

const handleResize = () => {
  pieChart?.resize()
  barChart?.resize()
  lineChart?.resize()
}

// 在组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  pieChart?.dispose()
  barChart?.dispose()
  lineChart?.dispose()
})
</script>

<style scoped>
.statistics-container {
  padding-top: 80px;
  padding-bottom: 32px;
  padding-left: 24px;
  padding-right: 24px;
  background: #f8fafc;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
  position: relative;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.statistics-header {
  margin-bottom: 48px;
  padding: 32px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  color: white;
}

.header-content {
  text-align: center;
}

.page-title {
  font-size: 36px;
  font-weight: 600;
  color: white;
  margin: 0 0 12px 0;
  letter-spacing: 0.5px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-subtitle {
  font-size: 18px;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1.6;
  font-weight: 400;
  margin: 0;
}

.statistics-overview {
  margin-bottom: 40px;
}

.el-row {
  width: 100%;
  margin: 0 !important;
}

.el-col {
  padding: 12px !important;
}

.stat-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: flex-start;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.04);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 20px;
  flex-shrink: 0;
}

.total-conferences .stat-icon { 
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
}

.published-conferences .stat-icon { 
  background: rgba(34, 197, 94, 0.1);
  color: #22c55e;
}

.upcoming-conferences .stat-icon { 
  background: rgba(234, 179, 8, 0.1);
  color: #eab308;
}

.total-venues .stat-icon { 
  background: rgba(168, 85, 247, 0.1);
  color: #a855f7;
}

.stat-info {
  flex: 1;
  min-width: 0;
}

.stat-number {
  font-size: 36px;
  font-weight: 600;
  line-height: 1.2;
  color: #1e293b;
  margin: 8px 0;
  white-space: nowrap;
}

.stat-label {
  font-size: 16px;
  color: #64748b;
  margin-bottom: 8px;
  font-weight: 500;
  white-space: nowrap;
}

.stat-unit {
  font-size: 14px;
  color: #94a3b8;
  white-space: nowrap;
  font-weight: 400;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  margin-top: 40px;
}

.chart-wrapper {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  height: 400px;
  display: flex;
  flex-direction: column;
}

.time-distribution {
  grid-column: 1 / -1;
  height: 400px;
}

.chart-header {
  margin-bottom: 16px;
  flex-shrink: 0;
}

.chart-header h3 {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 8px;
  letter-spacing: 0.3px;
}

.chart-description {
  font-size: 14px;
  color: #64748b;
  margin: 0;
  line-height: 1.5;
}

.chart-content {
  flex: 1;
  min-height: 300px;
  position: relative;
}

@media screen and (max-width: 1200px) {
  .el-col {
    width: 50% !important;
  }
  
  .page-title {
    font-size: 28px;
  }
  
  .page-subtitle {
    font-size: 15px;
  }
  
  .stat-number {
    font-size: 32px;
  }
  
  .stat-label {
    font-size: 15px;
  }
  
  .chart-header h3 {
    font-size: 18px;
  }
}

@media screen and (max-width: 768px) {
  .el-col {
    width: 100% !important;
  }
  
  .charts-grid {
    grid-template-columns: 1fr;
  }
  
  .chart-wrapper {
    height: 350px;
  }
  
  .stat-card {
    padding: 20px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
    margin-right: 12px;
  }
  
  .statistics-header {
    padding: 24px;
  }
  
  .page-title {
    font-size: 28px;
  }
  
  .page-subtitle {
    font-size: 16px;
  }
  
  .stat-number {
    font-size: 28px;
  }
  
  .stat-label {
    font-size: 14px;
  }
  
  .stat-unit {
    font-size: 13px;
  }
  
  .chart-header h3 {
    font-size: 16px;
  }
  
  .chart-description {
    font-size: 13px;
  }
}

@media screen and (max-width: 480px) {
  .statistics-container {
    padding: 80px 12px 20px;
  }

  .statistics-header {
    padding: 20px;
    margin-bottom: 32px;
  }

  .page-title {
    font-size: 24px;
  }

  .page-subtitle {
    font-size: 14px;
  }

  .stat-card {
    padding: 16px;
  }

  .stat-icon {
    width: 36px;
    height: 36px;
    font-size: 16px;
    margin-right: 12px;
  }

  .stat-number {
    font-size: 24px;
  }

  .chart-wrapper {
    height: 300px;
  }
}
</style> 